package com.antdant.service;

import com.antdant.entity.User;
import com.antdant.exception.GeneralException;
import com.antdant.repository.UserRepository;
import com.antdant.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/2/23 21:23
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    /**
     * 根据学号获取学生
     *
     * @param loginId 学号
     * @return
     */
    public User getUserByLoginId(String loginId) {
        User user = userRepository.findUserByLoginId(loginId);
        return user;
    }

    /**
     * 注册用户
     *
     * @param user
     * @return
     * @throws IOException
     */
    public User register(User user) throws IOException {
        //校验必填参数
        validate(user);
        //校验用户学(登录id)号唯一性
        validateUserExists(user.getLoginId());
        //注册用户
        User newUser = createNewUser();
        newUser.setLoginId(user.getLoginId());
        newUser.setUsername(user.getUsername());
        newUser.setPassword(PasswordUtils.getSHA256(user.getPassword()));
        return userRepository.save(newUser);
    }

    //创建新用户
    private User createNewUser() throws IOException {
        User user = new User();
        user.setCreateTime(DateUtils.getNowTime());
        //初始默认是普通用户
        user.setIsManager(0);
        //初始默认积分为0
        user.setPoint(0);
        //初始默认头像
        user.setAvatar(GrAvatarUtils.getBase64GrAvatar());
        //初始默认段位为白带
        user.setRankCode(10);
        return user;
    }

    //校验用户是否存在
    private void validateUserExists(String loginId) {
        //用户已经存在
        if (DataUtils.isNotNull(getUserByLoginId(loginId))) {
            throw new GeneralException("此学号已注册账号，请勿重复注册!");
        }
    }

    //校验用户注册参数
    private void validate(User user) {
        if (DataUtils.isEmptyStr(user.getLoginId())) {
            throw new GeneralException("学号为空");
        }
        if (DataUtils.isEmptyStr(user.getUsername())) {
            throw new GeneralException("用户名为空");
        }
        if (DataUtils.isEmptyStr(user.getPassword())) {
            throw new GeneralException("密码为空");
        }
    }

    /**
     * 根据id删除一个用户
     *
     * @param userId
     * @return
     */
    public boolean delete(Integer userId) {
        try {
            //TODO 删除与相关用户的外键联系

            userRepository.deleteById(userId);
            return true;
        } catch (RuntimeException e) {
            log.error("user delete failed,Error:", e);
            return false;
        }

    }

    /**
     * 根据用户id更新信息
     *
     * @param user
     * @return
     */
    public User modifyUser(User user)  {
        String password = user.getPassword();
        if (password.length() <= 16) {
            user.setPassword(PasswordUtils.getSHA256(password));
        }
        return userRepository.saveAndFlush(user);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId
     * @return
     */
    public User getUserById(Integer userId) {
        return userRepository.findById(userId).orElse(null);
    }

    /**
     * 分页查询用户
     *
     * @param current
     * @param size
     * @return
     */
    public Page<User> getAllUser(int current, int size, User user) {
        Pageable pageable = PageRequest.of(current - 1, size);
        return userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (DataUtils.isNotEmptyStr(user.getLoginId())) {
                    list.add(criteriaBuilder.like(root.get("loginId"), user.getLoginId()));
                }
                if (DataUtils.isNotEmptyStr(user.getUsername())) {
                    list.add(criteriaBuilder.like(root.get("username"), user.getUsername()));
                }
                if (user.getIsManager() != -1) {
                    list.add(criteriaBuilder.equal(root.get("isManager"), user.getIsManager()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    /**
     * 根据学号 重置密码
     *
     * @param loginId
     * @param password
     * @return
     */
    public User updatePassword(String loginId, String password) {
        User user = userRepository.findUserByLoginId(loginId);
        user.setPassword(PasswordUtils.getSHA256(password));
        return userRepository.saveAndFlush(user);
    }

    /**
     * 授权为管理员
     *
     * @param applyFromId
     */
    public User toBeManager(Integer applyFromId) {
        User user = getUserById(applyFromId);
        user.setIsManager(1);
        return userRepository.saveAndFlush(user);
    }

}
